package com.ng.framework.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class NGOSUtil {

	private static final Log LOG = LogFactory.getLog(NGOSUtil.class);

	public static final String EXEC_WINDOWS = " cmd /k ";

	public static final String EXEC_UNIX = " /bin/bash ";

	public static boolean isWindows() {
		String os = System.getProperty("os.name").toLowerCase();
		// windows
		return (os.indexOf("win") >= 0);

	}
	public static boolean isMac() {
		String os = System.getProperty("os.name").toLowerCase();
		// Mac
		return (os.indexOf("mac") >= 0);
	}
	public static boolean isUnix() {

		String os = System.getProperty("os.name").toLowerCase();
		// linux or unix
		return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0);
	}
	public static boolean isSolaris() {

		String os = System.getProperty("os.name").toLowerCase();
		// Solaris
		return (os.indexOf("sunos") >= 0);
	}

	public static void exec(String programAbsolutePath, String parameters, String[] environmentVariables, File baseDirectory) {

		String command = null;
		try {

			command = isUnix() ? getUnixCommand(programAbsolutePath, parameters) : getWindowsCommand(programAbsolutePath, parameters);

			Process p = Runtime.getRuntime().exec(command, environmentVariables, baseDirectory);

			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

			LOG.info("El comando invocado fue :" + command);

			/**
			 * Se lee la primera linea, al parecer esto hace que funcione
			 */
			br.readLine();

			// Mientras se haya leido alguna linea
			// while (aux != null) {
			// // Se escribe la linea en pantalla
			// System.out.println(aux);
			//
			// // y se lee la siguiente.
			// aux = br.readLine();
			// }
			LOG.info("El comando invocado finalizó :" + command);

		} catch (Exception e) {
			LOG.error("Excepcion mientras se ejecutaba el comando :" + command, e);
			e.printStackTrace();
		}
	}
	// cmd /k ""C:\Archivos de programa\NissiGroup\Expansion S.A.\mySqlRestore.bat" "C:\Documents and
	// Settings\vboxuser\Escritorio\Backup.sql"

	private static String getWindowsCommand(String programAbsolutePath, String parameters) {

		return EXEC_WINDOWS + "\"\"" + programAbsolutePath + "\" " + parameters + "\" ";

	}

	private static String getUnixCommand(String programAbsolutePath, String parameters) {

		return EXEC_UNIX + "" + programAbsolutePath + " " + parameters;

	}
	public static String getTempFolder() {
		if (isWindows()) {
			return System.getProperty("java.io.tmpdir") + File.separator;
		}
		return null;
	}

	public static String getExternalFilePath(String path, String externalFile) {

		String extension = ".sh";

		if (NGOSUtil.isWindows()) {
			extension = ".bat";
		}

		return path + File.separator + externalFile + extension;
	}
}
